﻿# -*- coding: utf-8 -*-
# DirHasher.py

# Copyright 2012 Ryan Schultz

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>

import hashlib, os

class DirHasher:
	"""Contains functions to generate hash for a directory."""
	#def __init__(self):
		
		
	def make_dir_hash(self, path, verbose = False):
		"""
		Return a hash of the contents of path.
		
		Keyword arguments:
		path -- Path to be hashed.
		verbose -- Show extra info? (default false)
		"""
		
		SHAhash = hashlib.sha1()
		
		# Raise an IOError if the directory doesn't exist.
		if not os.path.exists(path):
			print "ERROR: Directory to hash does not exist"
			raise IOError("Directory to hash does not exist: %s" % path)
			
		# Iterate over the directory and hash it.
		try:
			for root, dirs, files in os.walk(path):
				for name in files:
					file_path = os.path.join(root, name)
					
					if verbose == True:
						print 'INFO: Hashing %s' % file_path
					
					try:
						f1 = open(file_path, 'rb')
					except:
						# You can't open the file for some reason
						print "WARN: Couldn't open %s" % file_path
						f1.close()
						continue

					while True:
						# Read file in little chunks
						buf = f1.read(4096)
						if not buf : break
						SHAhash.update(hashlib.sha1(buf).hexdigest())
					
					f1.close()

		except:
			print "ERROR: Error while hashing directory %s" % path
			raise

		# No problems, so return the hash.
		return SHAhash.hexdigest()

if __name__ == "__main__":
	dh = DirHasher()
	hash = dh.make_dir_hash('TestDirectory', True)
	print "-----------------------"
	print hash